"""
ASR (Automatic Speech Recognition) API路由
提供语音识别接口
"""

from fastapi import APIRouter, HTTPException, UploadFile, File, Form
from services.asr import ASRService
from utils.logger import (
    emobot_logger,
    log_function_call,
    log_function_result,
    log_function_error,
)
from utils.performance_logger import (
    log_api_call,
    track_step
)
import time

logger = emobot_logger.get_logger()

router = APIRouter(prefix="/api/asr", tags=["asr"])


@router.post("/recognize")
async def recognize_audio(
    audio_file: UploadFile = File(..., description="音频文件"),
    task_id: str = Form(..., description="任务ID，由端侧提供")
):
    """
    语音识别接口
    
    Args:
        audio_file: 上传的音频文件
        task_id: 任务ID，由端侧传输提供
        
    Returns:
        识别结果
    """
    start_time = time.time()
    
    # 验证任务ID
    if not task_id or not task_id.strip():
        raise HTTPException(status_code=400, detail="任务ID不能为空")
    
    log_function_call("recognize_audio", {
        "filename": audio_file.filename,
        "content_type": audio_file.content_type,
        "task_id": task_id
    })
    
    emobot_logger.log_api_request(
        "POST", "/api/asr/recognize", {
            "filename": audio_file.filename,
            "content_type": audio_file.content_type,
            "task_id": task_id
        }
    )
    
    try:
        # 验证文件类型
        if not audio_file.content_type or not audio_file.content_type.startswith('audio/'):
            raise HTTPException(status_code=400, detail="Invalid audio file type")
        
        # 保存临时文件
        import tempfile
        import os
        
        with tempfile.NamedTemporaryFile(delete=False, suffix='.wav') as temp_file:
            content = await audio_file.read()
            temp_file.write(content)
            temp_file_path = temp_file.name
        
        try:
            # 调用ASR服务
            with track_step("ASR_RECOGNITION", {
                "task_id": task_id,
                "file_size": len(content)
            }):
                asr_service = ASRService()
                result = await asr_service.recognize_audio_file(temp_file_path, task_id)
            
            # 记录API调用
            log_api_call(
                api_name="ASR_RECOGNIZE_API",
                api_type="HTTP",
                request_data={
                    "task_id": task_id,
                    "file_size": len(content),
                    "filename": audio_file.filename
                }
            )
            
            duration = (time.time() - start_time) * 1000
            
            # 构建响应
            response = {
                "task_id": result.get("task_id", task_id),
                "text": result.get("text", ""),
                "confidence": result.get("confidence", 0.0),
                "duration": result.get("duration", 0.0),
                "timestamp": result.get("timestamp", time.time()),
                "success": result.get("success", False)
            }
            
            if not result.get("success", False):
                response["error"] = result.get("error", "Unknown error")
                emobot_logger.log_api_response(
                    "POST", "/api/asr/recognize", 500, response, duration
                )
                log_function_error("recognize_audio", Exception(result.get("error", "ASR failed")), {
                    "task_id": task_id,
                    "filename": audio_file.filename
                })
                raise HTTPException(status_code=500, detail=result.get("error", "ASR recognition failed"))
            
            emobot_logger.log_api_response(
                "POST", "/api/asr/recognize", 200, response, duration
            )
            log_function_result("recognize_audio", response, duration)
            
            return response
            
        finally:
            # 清理临时文件
            try:
                os.unlink(temp_file_path)
            except:
                pass
                
    except HTTPException:
        raise
    except Exception as e:
        duration = (time.time() - start_time) * 1000
        logger.error(f"ASR recognition failed: {e}")
        emobot_logger.log_api_response(
            "POST", "/api/asr/recognize", 500, {"error": str(e)}, duration
        )
        log_function_error("recognize_audio", e, {
            "task_id": task_id,
            "filename": audio_file.filename
        })
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/recognize-bytes")
async def recognize_audio_bytes(
    audio_data: bytes = File(..., description="音频字节数据"),
    task_id: str = Form(..., description="任务ID，由端侧提供")
):
    """
    语音识别接口（字节数据）
    
    Args:
        audio_data: 音频字节数据
        task_id: 任务ID，由端侧传输提供
        
    Returns:
        识别结果
    """
    start_time = time.time()
    
    # 验证任务ID
    if not task_id or not task_id.strip():
        raise HTTPException(status_code=400, detail="任务ID不能为空")
    
    log_function_call("recognize_audio_bytes", {
        "data_size": len(audio_data),
        "task_id": task_id
    })
    
    emobot_logger.log_api_request(
        "POST", "/api/asr/recognize-bytes", {
            "data_size": len(audio_data),
            "task_id": task_id
        }
    )
    
    try:
        # 调用ASR服务
        with track_step("ASR_RECOGNITION_BYTES", {
            "task_id": task_id,
            "data_size": len(audio_data)
        }):
            asr_service = ASRService()
            result = await asr_service.recognize_audio_bytes(audio_data, task_id)
        
        # 记录API调用
        log_api_call(
            api_name="ASR_RECOGNIZE_BYTES_API",
            api_type="HTTP",
            request_data={
                "task_id": task_id,
                "data_size": len(audio_data)
            }
        )
        
        duration = (time.time() - start_time) * 1000
        
        # 构建响应
        response = {
            "task_id": result.get("task_id", task_id),
            "text": result.get("text", ""),
            "confidence": result.get("confidence", 0.0),
            "duration": result.get("duration", 0.0),
            "timestamp": result.get("timestamp", time.time()),
            "success": result.get("success", False)
        }
        
        if not result.get("success", False):
            response["error"] = result.get("error", "Unknown error")
            emobot_logger.log_api_response(
                "POST", "/api/asr/recognize-bytes", 500, response, duration
            )
            log_function_error("recognize_audio_bytes", Exception(result.get("error", "ASR failed")), {
                "task_id": task_id,
                "data_size": len(audio_data)
            })
            raise HTTPException(status_code=500, detail=result.get("error", "ASR recognition failed"))
        
        emobot_logger.log_api_response(
            "POST", "/api/asr/recognize-bytes", 200, response, duration
        )
        log_function_result("recognize_audio_bytes", response, duration)
        
        return response
        
    except HTTPException:
        raise
    except Exception as e:
        duration = (time.time() - start_time) * 1000
        logger.error(f"ASR recognition failed: {e}")
        emobot_logger.log_api_response(
            "POST", "/api/asr/recognize-bytes", 500, {"error": str(e)}, duration
        )
        log_function_error("recognize_audio_bytes", e, {
            "task_id": task_id,
            "data_size": len(audio_data)
        })
        raise HTTPException(status_code=500, detail=str(e))
